#!/bin/sh /etc/rc.common
# Copyright (C) 2010-2018 OpenWrt.org

START=95
STOP=10

USE_PROCD=1

#PROCD_DEBUG=1

NAME=mysqld

LOGGER="/usr/bin/logger -p user.err -s -t $NAME"
COMMAND=/usr/bin/$NAME

mysqld_get_param() {
	$COMMAND --print-defaults \
		| tr " " "\n" \
		| grep -- "--$1" \
		| tail -n 1 \
		| cut -d= -f2
}

start_service() {
	local conf=/etc/mysql/my.cnf
	local dir
	local user=mariadb

	local datadir
	local logdir=/var/log/mysql
	local rundir=/var/run/mysqld
	local tmpdir

	local enabled
	local log_stderr
	local log_stdout
	local options

	if [ ! -x $COMMAND ]; then
		$LOGGER $COMMAND is missing
		exit 1
	fi

	if [ ! -r $conf ]; then
		$LOGGER $conf cannot be read
		exit 1
	fi

	config_load $NAME

	config_get_bool enabled general enabled 0
	if [ $enabled -eq 0 ]; then
		$LOGGER service not enabled in /etc/config/$NAME
		exit 1
	fi

	config_get_bool log_stderr general log_stderr 1
	config_get_bool log_stdout general log_stdout 1

	config_get options general options

	datadir=$(mysqld_get_param datadir)
	tmpdir=$(mysqld_get_param tmpdir)

	if [ -z "$datadir" ]; then
		$LOGGER datadir is not set
		exit 1
	fi

	if [ -z "$tmpdir" ]; then
		$LOGGER tmpdir is not set.
		exit 1
	fi

	[ -e "$datadir" ] || mkdir -p "$datadir"

	for dir in "$logdir" "$rundir" "$tmpdir"; do
		if [ ! -e "$dir" ]; then
			mkdir -p "$dir"
			chown $user "$dir"
		fi
	done

	if [ ! -f "$datadir/mysql/tables_priv.MYD" ]; then
		$LOGGER "cannot detect privileges table, you might need to"
		$LOGGER "run 'mysql_install_db --force' to initialize the system tables"
		exit 1
	fi

	procd_open_instance

	procd_set_param command $COMMAND $options

	# forward stderr to logd
	procd_set_param stderr $log_stderr
	# same for stdout
	procd_set_param stdout $log_stdout

	procd_close_instance
}

